import 'dart:math';
import 'package:flutter/material.dart';
import 'constant.dart';

class FlipCard extends StatefulWidget {
  //传入的参数
  const FlipCard({
    Key? key,
    required this.str,
    required this.isFront,
    required this.onTap,
    required this.isSelecting,
  }) : super(key: key);
  final String str;
  final bool isFront;
  final Function onTap;
  final isSelecting;

  @override
  _FlipCardState createState() => _FlipCardState();
}

class _FlipCardState extends State<FlipCard> {
  Widget _transitionBuilder(Widget child, Animation<double> animation) {
    final anim = Tween(begin: pi, end: 0).animate(animation);
    return AnimatedBuilder(
        animation: anim,
        builder: (context, widget) {
          return Transform(
            transform: Matrix4.rotationY(anim.value.toDouble()),
            child: child,
            alignment: Alignment.center,
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        widget.onTap.call();
      },
      child: AnimatedSwitcher(
        transitionBuilder: _transitionBuilder,
        duration: Duration(milliseconds: 500),
        child: widget.isFront
            ? MyCard(
                key: ValueKey(true),
                color: Color(0xFF4D48DA),
                str: widget.str, isSelecting: widget.isSelecting,
              )
            : MyCard(
                key: ValueKey(false),
                color: Colors.blue,
                str: '',
                isSelecting: widget.isSelecting,
              ),
      ),
    );
  }
}

class MyCard extends StatelessWidget {
  @override
  Key? get key => super.key;
  final String str;
  final Color color;
  final bool isSelecting;

  const MyCard(
      {Key? key,
      required this.str,
      required this.color,
      required this.isSelecting})
      : super(key: key);

  _borderSetting() {
    return isSelecting
        ? Border.all(
            color: Color(0xFF120BE5), width: 2, style: BorderStyle.solid)
        : null;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(
        str,
        style: TextStyle(fontSize: 24, color: Colors.white),
      ),
      key: key,
      width: cardSize - 4,
      margin: EdgeInsets.all(2),
      height: cardSize - 4,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          color: color,
          border: _borderSetting(),
          borderRadius: BorderRadius.circular(15)),
    );
  }
}
